package com.apexsoft.monitor.front.console.host.service;

import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.support.Result;
import com.apexsoft.front.common.utils.CryptUtil;
import com.apexsoft.monitor.front.console.host.dao.HostDao;
import com.apexsoft.monitor.front.console.host.om.Host;
import com.apexsoft.monitor.ssh.util.ShellUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service("hostService")
public class HostService {
    private static final Logger log = LogManager.getRootLogger();

    @Autowired
    @Qualifier("hostDao")
    private HostDao hostDao = null;

    /**
     * 分页面查询数据
     * @param page
     * @param hostName
     * @return
     * @throws Exception
     */
    public JSONObject listByPage(Pagination page, String hostName) throws Exception {
        EntityWrapper<Host> entityWrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(hostName)) {
            entityWrapper.like("host_name",hostName);
        }
        List<Host> list = hostDao.selectPage(page,entityWrapper);
        for(int i = 0;i<list.size();i++){
            Host host = list.get(i);
            try{
                String enUserPwd = CryptUtil.decode(host.getUserPwd(),"apexsoft"); //解密后
                String deUserPwd = CryptUtil.encode(enUserPwd,"test_pwd");   //再加密
                host.setUserPwd(deUserPwd);
            }catch (Exception e){

            }
        }
        JSONObject commonListResult = Result.commonListResult(list);
        commonListResult.put(Result.TOTAL,page.getTotal());
        return commonListResult;
    }

    /**
     * 新增主机
     * @param request
     * @return
     */
    public JSONObject add(HttpServletRequest request)throws Exception{
        JSONObject result = new JSONObject();
        String hostName = request.getParameter("hostName");
        String hostIp = request.getParameter("hostIp");
        String hostPort = request.getParameter("hostPort");
        String hostDesc = request.getParameter("hostDesc");
        String hostStatus = request.getParameter("hostStatus");
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String agentPort = request.getParameter("agentPort");
        //String enUserPwd = request.getParameter("enUserPwd"); //加密过的密码
        if(StringUtils.isNotBlank(hostName)
                && StringUtils.isNotBlank(hostIp)
                && StringUtils.isNotBlank(hostPort)
                && StringUtils.isNotBlank(hostStatus)
                && StringUtils.isNotBlank(userName)
                && StringUtils.isNotBlank(userPwd)
                && StringUtils.isNotBlank(agentPort)
                ){
            Host host = new Host();
            host.setHostName(hostName);
            host.setHostIp(hostIp);
            host.setHostPort(StringUtils.isNumeric(hostPort)?Integer.parseInt(hostPort):22);
            host.setHostStatus(StringUtils.isNumeric(hostStatus)?Integer.parseInt(hostStatus):0);
            host.setHostDesc(hostDesc);
            host.setUserName(userName);
            String deUserPwd = CryptUtil.decode(userPwd,"test_pwd"); //解密
            host.setUserPwd(CryptUtil.encode(deUserPwd,"apexsoft"));  //重新加密
            host.setAgentPort(Integer.parseInt(agentPort));
            try{
                long insertRst = hostDao.insertHost(host);
                if(insertRst > Result.EC_1000){
                    result.put(Result.CODE, Result.SC_0001);
                    result.put(Result.NOTE, "新增主机成功");
                }
            }catch (Exception e){
                log.error("新增主机失败："+e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "新增主机失败");
            }
        }else{
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "参数不正确");
        }
        return result;
    }

    /**
     * 更新主机
     * @param request
     * @return
     */
    public JSONObject update(HttpServletRequest request) throws Exception{
        JSONObject result = new JSONObject();
        String id = request.getParameter("id");
        String hostName = request.getParameter("hostName");
        String hostIp = request.getParameter("hostIp");
        String hostPort = request.getParameter("hostPort");
        String hostDesc = request.getParameter("hostDesc");
        String hostStatus = request.getParameter("hostStatus");
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String agentPort = request.getParameter("agentPort");
        //String enUserPwd = request.getParameter("enUserPwd"); //加密过的密码
        if(StringUtils.isNotBlank(hostName)
                && StringUtils.isNotBlank(hostIp)
                && StringUtils.isNotBlank(hostPort)
                && StringUtils.isNotBlank(hostStatus)
                && StringUtils.isNotBlank(userName)
                && StringUtils.isNotBlank(userPwd)
                && StringUtils.isNotBlank(agentPort)
                ){
            Host host = new Host();
            host.setId(Integer.parseInt(id));
            host.setHostName(hostName);
            host.setHostIp(hostIp);
            host.setHostPort(StringUtils.isNumeric(hostPort)?Integer.parseInt(hostPort):22);
            host.setHostStatus(StringUtils.isNumeric(hostStatus)?Integer.parseInt(hostStatus):0);
            host.setHostDesc(hostDesc);
            host.setUserName(userName);
            String deUserPwd = CryptUtil.decode(userPwd,"test_pwd"); //解密
            System.out.println("前端传来的数据解密后:"+deUserPwd);
            host.setUserPwd(CryptUtil.encode(deUserPwd,"apexsoft"));   //重新加密
            host.setAgentPort(Integer.parseInt(agentPort));
            try {
                int uptRst = hostDao.updateSelectiveById(host);
                if(uptRst > Result.EC_1000){
                    result.put(Result.CODE, Result.SC_0001);
                    result.put(Result.NOTE, "修改主机成功");
                }
            }catch (Exception e){
                log.error("修改主机失败："+e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "修改主机失败");
            }
        }else{
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "参数不正确");
        }
        return result;
    }

    /**
     * 删除主机
     * @param id
     * @return
     */
    public JSONObject delete(String id){
        JSONObject result = new JSONObject();
        if(StringUtils.isNotBlank(id)){
            try {
                int delRst = hostDao.deleteById(id);
                if(delRst>Result.EC_1000){
                    result.put(Result.CODE, Result.SC_0001);
                    result.put(Result.NOTE, "删除主机成功");
                }
            }catch (Exception e){
                log.error("删除主机失败："+e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "删除主机失败");
            }
        }
        return result;
    }

    /**
     * 查询单条记录
     * @param id
     * @return
     */
    public Host getById(int id){
        return hostDao.selectById(id);
    }

    public Host getByCode(String hostCode){
        return hostDao.selectByHostCode(hostCode);
    }

    /**
     * 查询所有状态正常的主机
     * @return
     */
    public JSONObject getAllHostByStatus() {
        EntityWrapper<Host> entityWrapper = new EntityWrapper<>();
        entityWrapper.and("host_status={0}",1);
        List<Host> list = hostDao.selectList(entityWrapper);
        return Result.commonListResult(list);
    }

    /**
     * 查询所有主机
     * @return
     */
    public JSONObject getAllHost() {
        EntityWrapper<Host> entityWrapper = new EntityWrapper<>();
        List<Host> list = hostDao.selectList(entityWrapper);
        return Result.commonListResult(list);
    }

    /**
     * 主机测试
     * @return
     */
    public JSONObject hostConnectTest(HttpServletRequest request){
        JSONObject result = new JSONObject();
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        String hostIp = request.getParameter("hostIp");
        String hostPort = request.getParameter("hostPort");
        if(StringUtils.isNotBlank(userName)
                && StringUtils.isNotBlank(userPwd)
                && StringUtils.isNotBlank(hostIp)
                && StringUtils.isNotBlank(hostPort)
                ){
            Host host = new Host();
            host.setUserName(userName);
            host.setUserPwd(userPwd);
            host.setHostIp(hostIp);
            host.setHostPort(Integer.parseInt(hostPort));
            ShellUtils shellUtils = new ShellUtils(host);
            result = shellUtils.connect();
        }else{
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "参数不正确");
        }
        return result;
    }
}
